package com.xwaf.platform.system.provider.serviceimpl.mqtt;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.xwaf.platform.system.api.entity.DataBase;
import com.xwaf.platform.system.api.entity.mqtt.IMMessage;
import com.xwaf.platform.system.api.entity.mqtt.IMUser;
import com.xwaf.platform.system.api.enums.MqttMessageStatus;
import com.xwaf.platform.system.api.service.mqtt.MqttMessageService;
import com.xwaf.platform.system.api.service.mqtt.MqttService;

@Service(value = "mqttMessageService")
public class MqttMessageServiceImpl implements MqttMessageService {

	@Autowired
	MqttService mqttService;

	@Override
	public void sendTestMessage(String chatNo, IMMessage message) {
		MqttMessageStatus topicType = MqttMessageStatus.TEST;
		sendMessage(topicType, chatNo, message);
	}

	@Override
	public void sendMessage(MqttMessageStatus topicStatus, String targetId, IMMessage message) {
		if (StringUtils.isEmpty(targetId)) {
			targetId = "0";
		}
		if (topicStatus == null) {
			topicStatus = MqttMessageStatus.OTHER;
		}
		if (StringUtils.isEmpty(message.getMessageId())) {
			message.setMessageId(DataBase.getDataBaseId(DataBase.MQTT));
		}
		if (message.getSender() == null) {
			message.setSender(IMUser.getSysUser());
		}
		if (message.getMessageTime() == null) {
			message.setMessageTime(new Date());
		}
		mqttService.sendMessage(topicStatus.getTopic() + "/" + targetId, JSON.toJSONString(message));
	}
}
